package com.heo.util;


public class TranscodingUtils {

	/**
	 * 字符串转换成十六进制字符串
	 * 
	 * @param String
	 *            str 待转换的ASCII字符串
	 * @return String 每个Byte之间空格分隔，如: [61 6C 6B]
	 */
	public static String str2HexStr(String str) {

		char[] chars = "0123456789ABCDEF".toCharArray();
		StringBuilder sb = new StringBuilder("");
		byte[] bs = str.getBytes();
		int bit;

		for (int i = 0; i < bs.length; i++) {
			bit = (bs[i] & 0x0f0) >> 4;
			sb.append(chars[bit]);
			bit = bs[i] & 0x0f;
			sb.append(chars[bit]);
			sb.append(' ');
		}
		return sb.toString().trim();
	}

	/**
	 * 十六进制转换字符串
	 * 
	 * @param String
	 *            str Byte字符串(Byte之间无分隔符 如:[616C6B])
	 * @return String 对应的字符串
	 */
	public static String hexStr2Str(String hexStr) {
		String str = "0123456789ABCDEF";
		char[] hexs = hexStr.toCharArray();
		byte[] bytes = new byte[hexStr.length() / 2];
		int n;

		for (int i = 0; i < bytes.length; i++) {
			n = str.indexOf(hexs[2 * i]) * 16;
			n += str.indexOf(hexs[2 * i + 1]);
			bytes[i] = (byte) (n & 0xff);
		}
		return new String(bytes);
	}

	/**
	 * bytes转换成十六进制字符串
	 * 
	 * @param byte[] b byte数组
	 * @return String 每个Byte值之间空格分隔
	 */
	public static String byte2HexStr(byte[] b) {
		String stmp = "";
		StringBuilder sb = new StringBuilder("");
		for (int n = 0; n < b.length; n++) {
			stmp = Integer.toHexString(b[n] & 0xFF);
			sb.append((stmp.length() == 1) ? "0" + stmp : stmp);
			sb.append(" ");
		}
		return sb.toString().toUpperCase().trim();
	}

	/**
	 * bytes字符串转换为Byte值
	 * 
	 * @param String
	 *            src Byte字符串，每个Byte之间没有分隔符
	 * @return byte[]
	 */
	public static byte[] hexStr2Bytes(String src) {
		int m = 0, n = 0;
		int l = src.length() / 2;
		byte[] ret = new byte[l];
		for (int i = 0; i < l; i++) {
			m = i * 2 + 1;
			n = m + 1;
			ret[i] = Byte.decode(src.substring(i * 2, m) + src.substring(m, n));
		}
		return ret;
	}

	/**
	 * String的字符串转换成unicode的String
	 * 
	 * @param String
	 *            strText 全角字符串
	 * @return String 每个unicode之间无分隔符
	 * @throws Exception
	 */
	public static String strToUnicode(String strText) throws Exception {
		char c;
		StringBuilder str = new StringBuilder();
		int intAsc;
		String strHex;
		for (int i = 0; i < strText.length(); i++) {
			c = strText.charAt(i);
			intAsc = (int) c;
			strHex = Integer.toHexString(intAsc);
			if (intAsc > 128)
				str.append("\\u" + strHex);
			else
				// 低位在前面补00
				str.append("\\u00" + strHex);
		}
		return str.toString();
	}

	/**
	 * unicode的String转换成String的字符串
	 * 
	 * @param String
	 *            hex 16进制值字符串 （一个unicode为2byte）
	 * @return String 全角字符串
	 */
	public static String unicodeToString(String hex) {
		int t = hex.length() / 6;
		StringBuilder str = new StringBuilder();
		for (int i = 0; i < t; i++) {
			String s = hex.substring(i * 6, (i + 1) * 6);
			// 高位需要补上00再转
			String s1 = s.substring(2, 4) + "00";
			// 低位直接转
			String s2 = s.substring(4);
			// 将16进制的string转为int
			int n = Integer.valueOf(s1, 16) + Integer.valueOf(s2, 16);
			// 将int转换为字符
			char[] chars = Character.toChars(n);
			str.append(new String(chars));
		}
		return str.toString();
	}

	// byte数字转字符串
	public static String printHexString(byte[] b) {
		String hexs = "";
		for (int i = 0; i < b.length; i++) {

			String hex = Integer.toHexString(b[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			hexs += hex;

		}
		return hexs;
	}

	public static void main(String[] args) {
		byte[] b = new byte[4];
		b[0] = (byte) 0xAA;
		b[1] = (byte) 0x01;
		b[2] = (byte) 0x02;
		b[3] = (byte) 0x03;
		System.out.println(TranscodingUtils.byte2HexStr(b));
		// 030204000BCB55
		String code = "AA030204000BCB55";
		// System.out.println(Byte.parseByte("AA"));
		System.out.println(hexIntegerToBytes(31, 4));
		
		System.out.println("16 - 2 = "+hexString2binaryString("80"));
		
		System.out.println("2 - 16 = "+binaryString2hexString("10000000"));
		
		double calc = 29d;
		System.out.println(Utils.getDoubleFormatDouble(8/calc));
		
		int water = 9;
		int max = (int) (water * calc);
		System.out.println(max);
		String hex = hex10To16(max, 4);
		System.out.println(hex);
		System.out.println(hex16To10(hex));
		
		System.out.println("passagewaySort");
		int passagewaySort = 5;
		StringBuilder sbBuilder = new StringBuilder("00000000");
		sbBuilder.replace(passagewaySort - 1, passagewaySort, "1");
		System.out.println(sbBuilder +  "-----" + "00000000".equals(sbBuilder.toString()));
		String binaryStr = TranscodingUtils.binaryString2hexString(sbBuilder.toString());
		StringBuilder sendCode = new StringBuilder("F1F11501");
		sendCode.append(binaryStr);
		sendCode.append(CRC16.calcCrc16(sendCode.toString()));
		System.out.println(sendCode);
	}
	
	/**
	 * 16进制转2进制  返回字符串
	 * @param hexString
	 * @return
	 */
	public static String hexString2binaryString(String hexString)  
    {  
        if (hexString == null || hexString.length() % 2 != 0)  
            return null;  
        String bString = "", tmp;  
        for (int i = 0; i < hexString.length(); i++)  
        {  
            tmp = "0000" + Integer.toBinaryString(Integer.parseInt(hexString  
                            .substring(i, i + 1), 16));  
            bString += tmp.substring(tmp.length() - 4);  
        }  
        return bString;  
    }
	
	/**
	 * 2进制转16进制  返回字符串
	 * @param bString
	 * @return
	 */
	public static String binaryString2hexString(String bString)  
    {  
        if (bString == null || bString.equals("") || bString.length() % 8 != 0)  
            return null;  
        StringBuffer tmp = new StringBuffer();  
        int iTmp = 0;  
        for (int i = 0; i < bString.length(); i += 4)  
        {  
            iTmp = 0;  
            for (int j = 0; j < 4; j++)  
            {  
                iTmp += Integer.parseInt(bString.substring(i + j, i + j + 1)) << (4 - j - 1);  
            }  
            tmp.append(Integer.toHexString(iTmp));  
        }  
        return tmp.toString();  
    }  

	public static int hex16To10(String code) {
		return Integer.parseInt(code, 16);
	}
	
	public static String hex16To10(String code, int length) {
		StringBuilder codeStart = new StringBuilder(code.substring(0, 2));
		String codes = code.substring(2);
		int codeInt = Integer.parseInt(codes, 16);
		int size = length - String.valueOf(codeInt).length();
		for(int i = 0; i < size; i++){
			codeStart.append("0");
		}
		codeStart.append(codeInt);
		return codeStart.toString();
	}

	public static String hex10To16(int hex) {
		return Integer.toHexString(hex);
	}
	
	public static String hex10To16(int hex, int length) {
		String hexs = Integer.toHexString(hex);
		StringBuilder codeStart = new StringBuilder();
		int size = length - String.valueOf(hexs).length();
		for(int i = 0; i < size; i++){
			codeStart.append("0");
		}
		codeStart.append(hexs);
		return codeStart.toString();
	}

	public static byte[] hexStringToBytes(String hexString) {
		if (hexString == null || hexString.equals("")) {
			return null;
		}
		hexString = hexString.toUpperCase();
		int length = hexString.length() / 2;
		char[] hexChars = hexString.toCharArray();
		byte[] d = new byte[length];
		for (int i = 0; i < length; i++) {
			int pos = i * 2;
			d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
		}
		return d;
	}

	/**
	 * Convert char to byte
	 * 
	 * @param c
	 *            char
	 * @return byte
	 */
	private static byte charToByte(char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}

	/**
	 * String的字符串转换成unicode的String
	 * 
	 * @param String
	 *            strText 全角字符串
	 * @return String 每个unicode之间无分隔符
	 * @throws Exception
	 */
	public static String hexIntegerToBytes(int code, int length) {
		String str = "";
		if (code > 65535) {
			return "0000";
		}
		str = Integer.toHexString(code);
		int len = str.length();
		if (len == length) {
			return str;
		}

		for (int i = 0; i < length - len; i++) {
			str = "0" + str;
		}
		return str.toUpperCase();
	}
}
